package com.gugu.procedure.service;


import com.gugu.procedure.bean.MenuRoleRel;
import com.gugu.procedure.common.MessageResult;
import com.gugu.procedure.dao.MenuRoleRelDao;
import com.gugu.procedure.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class MenuRoleRelService {

    @Autowired
    private MenuRoleRelDao menuRoleRelDao;

    public MessageResult save(MenuRoleRel menuRoleRel) {
        MenuRoleRel rel = menuRoleRelDao.findTopByRole(menuRoleRel.getRole());
        if (Objects.nonNull(rel)) {
            rel.setMenus(menuRoleRel.getMenus());
            menuRoleRelDao.save(rel);
            return MessageResult.success();
        }
        menuRoleRel.setCreateTime(DateUtil.getFormatedDateTime());
        menuRoleRelDao.save(menuRoleRel);
        return MessageResult.success();
    }

    public MessageResult delete(Long id) {
        menuRoleRelDao.deleteById(id);
        return MessageResult.success();
    }

    public MenuRoleRel findByRole(String role) {
        return menuRoleRelDao.findTopByRole(role);
    }

    public MessageResult page(String role, int pageNo, int pageSize) {
        Specification<MenuRoleRel> spec = (Specification<MenuRoleRel>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasText(role)) {
                list.add(cb.equal(root.get("role").as(String.class), role));
            }
            Predicate[] pre = new Predicate[list.size()];
            query.where(list.toArray(pre));
            return query.getRestriction();
        };
        PageRequest pr = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime");
        Page<MenuRoleRel> recordsPage = menuRoleRelDao.findAll(spec, pr);
        MessageResult mr = MessageResult.success();
        mr.setTotal(recordsPage.getTotalElements());
        mr.setTotalElement(recordsPage.getContent());
        return mr;
    }


}
